﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.IO;

public partial class Pages_Principal : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void lnkExcel_Click(object sender, EventArgs e)
    {
        try
        {
            //Buscar grid del content page
            GridView grdGridDatos = (GridView)ContentPlaceHolder1.FindControl("GridView1");
            if (grdGridDatos.Rows.Count > 0)
            {
                grdGridDatos.AllowPaging = false;
                grdGridDatos.DataBind();
                Export("Consultas Intranet.xls", grdGridDatos);
            }
        }
        catch (Exception ex)
        {

            throw new Exception("error al exportar a excel. " + ex.Message);
        }
    }
    protected void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        //  Crear una tabla para contener el grid
        Table table = new Table();

        //Agrega titulo de la pagina
        lblTitulo.RenderControl(htw);

        //Enviar control sin datos, para generar linea en blanco.
        lblVacio.RenderControl(htw);

        table.RenderControl(htw);

        //Adicionar encabezado si existe
        HtmlTable htmTabla = (HtmlTable)ContentPlaceHolder1.FindControl("TablaHeader");
        if (htmTabla != null)
        {
            htmTabla.Border = 1;
            htmTabla.BorderColor = "Red";
            htmTabla.RenderControl(htw);
        }
        //Enviar control sin datos, para generar linea en blanco.
        lblVacio.RenderControl(htw);

        //  add the header row to the table
        if (gv.HeaderRow != null)
        {
            PrepareControlForExport(gv.HeaderRow);
            table.Rows.Add(gv.HeaderRow);
        }

        //  add each of the data rows to the table
        foreach (GridViewRow row in gv.Rows)
        {
            PrepareControlForExport(row);
            table.Rows.Add(row);
        }

        //  add the footer row to the table
        if (gv.FooterRow != null)
        {
            PrepareControlForExport(gv.FooterRow);
            table.Rows.Add(gv.FooterRow);
        }

        //  render the table into the htmlwriter
        table.GridLines = GridLines.Both;
        table.RenderControl(htw);

        //  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    protected void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }

    //protected void Export2()
    //{
    //    string attachment = "attachment; filename=Contacts.xls";
    //    Response.ClearContent();
    //    Response.AddHeader("content-disposition", attachment);
    //    Response.ContentType = "application/ms-excel";
    //    StringWriter sw = new StringWriter();
    //    HtmlTextWriter htw = new HtmlTextWriter(sw);
    //    // Create a form to contain the grid
    //    HtmlForm frm = new HtmlForm();
    //    frm.Attributes["runat"] = "server";
    //    foreach (Control tControl in this.Controls)
    //    {
    //        frm.Controls.Add(tControl);
    //    }
    //    frm.RenderControl(htw);
    //    //GridView1.RenderControl(htw);
    //    Response.Write(sw.ToString());
    //    Response.End();
    //}
}

